using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using LitJson;

//	BTree.cs




namespace Game.AIBehaviorTree
{
	/// <summary>
	/// Behavior tree.
	/// </summary>
	public class BTree : ScriptableObject
    {
        //描述
        public string strTreeName;
        //root 
        public BNode nodeRoot;

        //未被激活的BT不会执行
        public bool isActive = true;
        

        public BTree()
		{
		}

		//set root node
		public void SetRoot( BNode node )
		{
			this.nodeRoot = node;
		}

		//clear root node
		public void Clear()
		{
			this.nodeRoot = null;
		}

		public void Run( BTDashBoard input )
		{
            if (!isActive) return;
			this.nodeRoot.RunNode(input);
		}

        #region Initialize
        public static BTree CloneTree(BTree behaviorTree)
        {
            BTree treeClone = Instantiate<BTree>(behaviorTree);
            treeClone.nodeRoot = behaviorTree.nodeRoot.clone(null);
            return treeClone;
        }

       
        #endregion

        #region Utility Methods
        //write json
        public void WriteJson(JsonData parent)
        {
            JsonData json = new JsonData();
            json["name"] = this.strTreeName;
            if (this.nodeRoot != null)
            {
                json["node"] = new JsonData();
                json["node"].SetJsonType(JsonType.Object);
                json["node"] = this.nodeRoot.WriteJson();
            }
            parent.Add(json);
        }

        //read json
        public void ReadJson(JsonData json)
        {
            this.strTreeName = json["name"].ToString();
            this.nodeRoot = null;
            if (json.Keys.Contains("node"))
            {
                string typename = json["node"]["type"].ToString();
                Type t = Type.GetType(typename);
                this.nodeRoot = Activator.CreateInstance(t) as BNode;
                this.nodeRoot.ReadJson(json["node"]);
            }
        }
        #endregion
    }

}

